﻿using DoNet.Common.Helpers;
using Microsoft.Extensions.Options;

namespace WechatMp.Web
{
    /// <summary>
    /// 
    /// </summary>
    public class ServicesHelper
    {
        /// <summary>
        /// 
        /// </summary>
        public static IServiceProvider? serviceProvider;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_services"></param>
        public ServicesHelper(IServiceCollection _services)
        {
            ConfigHelper.services = _services;
            var services = ConfigHelper.services;
            if (services != null)
                serviceProvider = services?.BuildServiceProvider();
        }

        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object? GetService(Type type)
        {
            return serviceProvider?.GetService(type);
        }
        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <returns></returns>
        public static TService? GetService<TService>() where TService : class
        {
            return GetService(typeof(TService)) as TService;
        }
        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <returns></returns>
        public static TService? GetRequiredService<TService>() where TService : class
        {
            return GetRequiredService(typeof(TService)) as TService;
        }
        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object? GetRequiredService(Type type)
        {
            return serviceProvider?.GetRequiredService(type);
        }
        /// <summary>
        /// 获取选项
        /// </summary>
        /// <typeparam name="TOptions">强类型选项类</typeparam>
        /// <returns>TOptions</returns>
        public static TOptions? GetOptions<TOptions>() where TOptions : class, new()
        {
            return GetService<IOptions<TOptions>>()?.Value;
        }
        /// <summary>
        /// 获取选项
        /// </summary>
        /// <typeparam name="TOptions">强类型选项类</typeparam>
        /// <returns>TOptions</returns>
        public static TOptions? GetOptionsMonitor<TOptions>() where TOptions : class, new()
        {
            return GetService<IOptionsMonitor<TOptions>>()?.CurrentValue;
        }
        /// <summary>
        /// 获取选项
        /// </summary>
        /// <typeparam name="TOptions">强类型选项类</typeparam>
        /// <returns>TOptions</returns>
        public static TOptions? GetOptionsSnapshot<TOptions>() where TOptions : class, new()
        {
            return GetService<IOptionsSnapshot<TOptions>>()?.Value;
        }
    }
}
